package org.example.aigc.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.example.aigc.service.ChatService;
import org.springframework.stereotype.Service;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

@Service
public class ChatServiceImpl implements ChatService {

    public String chat(String query,String knowledgeBaseName) {
        MyJson myJson = new MyJson();
        myJson.setQuery(query);
        myJson.setKnowledge_base_name(knowledgeBaseName);
        myJson.setTop_k(3);
        myJson.setScore_threshold(1.0F);
        myJson.setModel("chatglm3-6b");
        myJson.setTemperature(0.7F);
        String jsonstr = JSONObject.toJSONString(myJson);  // 转换为json字符串
        return postEventStream(jsonstr);
    }
    public String postEventStream(String json) {
        InputStream is = null;
        //11.读取输入流中的返回值
        StringBuffer bu = new StringBuffer();
        try {
            //1.设置URL
            URL url = new URL("http", "172.26.94.12", 7861, "/chat/knowledge_base_chat");
            //2.打开URL连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //3.设置请求方式
            conn.setRequestMethod("POST");
            //4.设置Content-Type
            conn.setRequestProperty("Content-Type", "application/json;charset=StandardCharsets.UTF_8");
            //5.设置Accept
            conn.setRequestProperty("Accept", "text/event-stream");
            //6.设置DoOutput
            conn.setDoOutput(true);
            //7.设置DoInput
            conn.setDoInput(true);
            //8.获取输出流
            OutputStream os = conn.getOutputStream();
            //9.写入参数（json格式）
            os.write(json.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();
            //10.获取输入流
            is = conn.getInputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                String line = new String(bytes, 0, len, StandardCharsets.UTF_8);
                bu.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException();
        } finally {
            if (!Objects.isNull(is)) {
                try {
                    //12.关闭输入流
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        String data = bu.toString();
        String s = data.substring(6);
        JSONObject object = JSON.parseObject(s);
        return object.getString("answer");
    }
    class MyJson{
        String query;
        String knowledge_base_name;
        int top_k;
        float score_threshold;
        boolean stream=false;
        String model;
        float temperature;
        int max_tokens;

        public String getQuery() {
            return query;
        }

        public void setQuery(String query) {
            this.query = query;
        }

        public String getKnowledge_base_name() {
            return knowledge_base_name;
        }

        public void setKnowledge_base_name(String knowledge_base_name) {
            this.knowledge_base_name = knowledge_base_name;
        }

        public int getTop_k() {
            return top_k;
        }

        public void setTop_k(int top_k) {
            this.top_k = top_k;
        }

        public float getScore_threshold() {
            return score_threshold;
        }

        public void setScore_threshold(float score_threshold) {
            this.score_threshold = score_threshold;
        }

        public boolean isStream() {
            return stream;
        }

        public void setStream(boolean stream) {
            this.stream = stream;
        }

        public String getModel() {
            return model;
        }

        public void setModel(String model) {
            this.model = model;
        }

        public float getTemperature() {
            return temperature;
        }

        public void setTemperature(float temperature) {
            this.temperature = temperature;
        }

        public int getMax_tokens() {
            return max_tokens;
        }

        public void setMax_tokens(int max_tokens) {
            this.max_tokens = max_tokens;
        }
    }
}
